import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { Menus, ViewPath } from '@/utils/global'
import { setupRouterGuard } from './guard'
import type { App } from 'vue'

const modules = import.meta.glob('../views/**/**/*.vue')

const getChildren = (menu: Menu) => {
	return Menus.filter((ele) => ele.parentId === menu.id).map((ele) => {
		const res = {
			path: ele.path,
			name: ele.label
		} as RouteRecordRaw
		if (ele.isLeaf) {
			res.component = modules[`../views${ele.path}/Index.vue`]
		} else {
			res.children = getChildren(ele)
		}
		return res
	})
}

const routes: RouteRecordRaw[] = Menus.filter((ele) => !ele.parentId).map((ele) => {
	const route = {} as RouteRecordRaw
	route.component = () => import('@/layout/Index.vue')
	if (ele.isLeaf) {
		route.path = '/'
		route.redirect = ViewPath.Home
		route.children = [
			{
				path: ele.path,
				name: ele.label,
				component: modules[`../views${ele.path}/Index.vue`]
			}
		]
	} else {
		route.path = ele.path
		route.name = ele.label
		route.children = getChildren(ele)
	}
	return route
})

const router = createRouter({
	history: createWebHistory(),
	routes
})

export default router

export const setupRouter = async (app: App) => {
	setupRouterGuard()
	app.use(router)
}
